package com.manner.groupon.service.store.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.manner.groupon.common.BaseResponse;
import com.manner.groupon.common.PageResult;
import com.manner.groupon.common.ResultUtils;
import com.manner.groupon.exception.CustomException;
import com.manner.groupon.mapper.WithDrawRecordMapper;
import com.manner.groupon.model.dto.order.AdminWithDTO;
import com.manner.groupon.model.dto.store.WithDrawDTO;
import com.manner.groupon.model.entity.StoreLinkMan;
import com.manner.groupon.model.entity.SysDict;
import com.manner.groupon.model.entity.WithDrawRecord;
import com.manner.groupon.model.enums.RoleEnums;
import com.manner.groupon.model.vo.AdminWithVO;
import com.manner.groupon.service.store.StoreLinkManService;
import com.manner.groupon.service.store.WithDrawRecordService;
import com.manner.groupon.service.sys.SysDictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static com.manner.groupon.constant.CommonConstant.DRAW_FEE;
import static com.manner.groupon.constant.CommonConstant.MIN_DRAW_AMOUNT;

@Service
@Slf4j
public class WithDrawRecordServiceImpl extends ServiceImpl<WithDrawRecordMapper, WithDrawRecord> implements WithDrawRecordService {

    @Resource
    private StoreLinkManService storeLinkManService;

    @Resource
    private WithDrawRecordMapper withDrawRecordMapper;

    @Resource
    private SysDictService service;

    @Override
    public BaseResponse<String> insert(WithDrawDTO withDrawDTO) {
        //获取商家信息
        StoreLinkMan linkMan = storeLinkManService.query().eq("phone", withDrawDTO.getPhone()).one();
        //获取最小提现金额
        SysDict drawAmount = service.query().eq("name", MIN_DRAW_AMOUNT).one();
        //转换
        BigDecimal bigDecimal = new BigDecimal(drawAmount.getValue());
        //比较大小
        if (linkMan.getBookBalance().compareTo(bigDecimal) < 0) {
            throw new CustomException("不好意思,提现金额不能小于" + bigDecimal + "元");
        }
        //判断是否还有正在审核的
        Long count = query().eq("payee_name", linkMan.getLinkmanName()).eq("status", 0).count();
        //判断
        if (count > 0) {
            throw new CustomException("不好意思,您当前正有一笔提现正在审核中");
        }
        //查询手续费
        SysDict key = service.query().eq("name", DRAW_FEE).one();
        BigDecimal fee = new BigDecimal(key.getValue());
        fee = fee.movePointLeft(2);
        //算出手续费
        BigDecimal drawFee = withDrawDTO.getPrice().multiply(fee);
        //实际提现金额
        BigDecimal drawPrice = withDrawDTO.getPrice().subtract(drawFee);
        //设置数据
        WithDrawRecord withDrawRecord = new WithDrawRecord(null, linkMan.getPayeeName(), linkMan.getPhone(), null, null, withDrawDTO.getIdentity(), "银行卡支付", null, linkMan.getRemitAccount(),
                withDrawDTO.getPrice(), drawFee, drawPrice, 0, null, null, null);
        //增加数据
        log.info("手续费为 : {}, 提现金额为 : {}, 提现百分比为 : {}", drawFee, drawPrice, fee);
        save(withDrawRecord);
        //返回数据
        return ResultUtils.success("提现成功,请等待审核");
    }

    @Override
    public BaseResponse<List<WithDrawRecord>> list_search(String phone) {
        //查询商户门店联系人信息
        StoreLinkMan storeLinkman = storeLinkManService.query().eq("phone", phone).one();
        //查询
        List<WithDrawRecord> withDrawRecords = query().eq("payee_name", storeLinkman.getLinkmanName()).list();
        //返回数据
        return ResultUtils.success(withDrawRecords);
    }

    @Override
    public BaseResponse<PageResult<AdminWithVO>> query_search(AdminWithDTO adminWithDTO) {
        //构建分页对象
        Page<WithDrawRecord> page = new Page<>(adminWithDTO.getCurrent(), adminWithDTO.getPageSize());
        //查询
        QueryWrapper<WithDrawRecord> wrapper = new QueryWrapper<>();
        //判断
        if (StrUtil.isNotBlank(adminWithDTO.getName())) {
            wrapper.like("payee_name", '%' + adminWithDTO.getName() + '%');
        }
        if (adminWithDTO.getStatus() != 4) {
            wrapper.eq("status", adminWithDTO.getStatus());
        }
        wrapper.orderByDesc("create_time");
        //查询数据
        Page<WithDrawRecord> result = withDrawRecordMapper.selectPage(page, wrapper);
        //准备容器
        List<AdminWithVO> container = new ArrayList<>();
        //遍历构建
        result.getRecords().forEach(item -> {
            //获取联系人信息
            StoreLinkMan linkMan = storeLinkManService.query().eq("linkman_name", item.getPayeeName()).one();
            //添加进入容器
            container.add(new AdminWithVO(item.getId(), item.getPayeeName(), item.getPayeePhone(), item.getStoreName(), item.getStoreLinkManPhone(),
                    item.getIdentity(), item.getWay(), item.getCollectMoneyOnWechat(), item.getCreditCardNumbers(), item.getPrice(), item.getFee(), item.getMoney(),
                    item.getStatus(), item.getRemark(), item.getCreateTime(), item.getUpdateTime(), linkMan.getRemitAccount()));
        });
        //返回数据
        return ResultUtils.success(new PageResult<>(container, result.getTotal()));
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public BaseResponse<String> updateWith(Long id) {
        //查询提现账单
        WithDrawRecord withDrawRecord = getById(id);
        //先查看总账户钱够不够
        StoreLinkMan linkMan = storeLinkManService.query().eq("role", RoleEnums.ADMIN_ROLE.getId()).one();
        //获取提现商家
        StoreLinkMan storeLinkMan = storeLinkManService.query().eq("role", RoleEnums.STORE_ROLE.getId()).eq("linkman_name", withDrawRecord.getPayeeName()).one();
        //判断总账户钱够不够
        int result = withDrawRecord.getPrice().compareTo(linkMan.getBookBalance());
        //判读
        if (result == 1) {
            throw new CustomException("不好意思,总账户余额不足");
        }
        //判断自己的钱够不够
        int compareTo = withDrawRecord.getPrice().compareTo(storeLinkMan.getBookBalance());
        //判断
        if (compareTo == 1) {
            throw new CustomException("不好意思,用户余额不足");
        }
        //划钱过去
        linkMan.setBookBalance(linkMan.getBookBalance().subtract(withDrawRecord.getPrice()));
        storeLinkMan.setBookBalance(storeLinkMan.getBookBalance().subtract(withDrawRecord.getPrice()));
        //修改数据
        storeLinkManService.updateById(linkMan);
        storeLinkManService.updateById(storeLinkMan);
        //修改提现状态
        update().set("status", 1).eq("id", id).update();
        //返回数据
        return ResultUtils.success("审核成功");
    }
}
